import 'dart:io';

import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/common/event_bus.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/login&register/model/shared_user_info.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_pickers/Media.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:find_friend/const/const.dart';

import '../mine_photos_wall.dart';

class PhotoWallWidget extends StatefulWidget {
  
  final List<FileModel> list;

  final Size size;

  const PhotoWallWidget({Key key, this.list, this.size}) : super(key: key);

  @override
  _PhotoWallWidgetState createState() => _PhotoWallWidgetState();
}

class _PhotoWallWidgetState extends State<PhotoWallWidget> {
  _photo(BuildContext context) async {
    var image = await ImagePicker.pickImage(source: ImageSource.camera, imageQuality: 90, maxHeight: widget.size.width);
    if(image != null){
      _uploadImage(context, [image]);
    }
  }

  _album(BuildContext context) async {
    List<Media> _listImagePaths = await ImagePickers.pickerPaths(
      galleryMode: GalleryMode.image,
      selectCount: 6 - widget.list.length,
      showCamera: false,
      // cropConfig :CropConfig(enableCrop: true,height: 1,width: 1),
      // compressSize: 500,
    );
    List<File> _temp = [];
    _listImagePaths.forEach((e) { _temp.add(File(e.path)); });
    _uploadImage(context, _temp);
  }

  _uploadImage(BuildContext context, List<File> images) {
    AlertTool.showLoadingDialog(context,"正在上传...");
    Networktool.uploads(API.photowall, images, (data) {
      if(data["data"] != null) {
        SharedUserInfo.saveData(data);
        EventMineBus.instance.commit(EventMineKeys.UpdateMineInfo, null);
      }

      setState(() {
        
      });
    },
    fail: (msg) => AlertTool.showToast(msg),
    finaly: () => Navigator.of(context).pop()
    );
  }

  @override
  Widget build(BuildContext context) {

    int count = 1;
    if(widget.list == null) {
    } else if(widget.list != null && widget.list.length < 6){
      count += widget.list.length;
    } else {
      count = widget.list.length;
    }

    return Container(
          height: 85.h,
          margin: const EdgeInsets.symmetric(horizontal: 10),
          child: ListView.builder(
            itemCount: count,
            itemExtent: 85.h - 10,
            padding: const EdgeInsets.only(top: 9.5, bottom: 10),
            scrollDirection: Axis.horizontal,
            itemBuilder: (context, index){
              final tagStr = "avatar" + index.toString();
              if(index == count - 1 && widget.list.length < 6) {
                return Container(
                decoration: BoxDecoration(
                  color: const Color(0x33ffffff),
                  border: Border.all(color:Colors.black12, width: 0.5),
                  borderRadius: BorderRadius.circular(5)
                ),
                child: IconButton(
                    onPressed: (){
                      AlertTool.showBottomDialog(context, ["拍照", "从手机相册选择"], onTapIndex: (index){
                        switch (index) {
                          case 0:
                            _photo(context);
                            break;
                          case 1:
                            _album(context);
                            break;
                        }
                        Navigator.of(context).pop();
                      });
                    },
                    icon: Image.asset("assets/+.png"),
                  ),
                );
              } else {
                return GestureDetector(
                            onTap: () async {
                              Navigator.push(context, PageRouteBuilder(
                                  pageBuilder: (BuildContext context, Animation animation,
                                      Animation secondaryAnimation) {
                                    return new FadeTransition(
                                      opacity: animation,
                                      child: MinePhotoWallPage(heroTag: tagStr, list: widget.list, isowner: true,),
                                    );
                                  })
                              );
                            },
                            child: Container(
                              padding: const EdgeInsets.only(right: 5), // 必须要限定hero动画的大小
                              child: Card(
                                margin: const EdgeInsets.all(0),
                                semanticContainer: true,
                                color: Colors.transparent,
                                clipBehavior: Clip.antiAlias,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(8.0),
                                ),
                                elevation: 3,
                                child: Hero(
                                  tag: tagStr,
                                  child: Image.network(
                                      widget.list[index].url ?? "",
                                      fit: BoxFit.cover,
                                    )
                                ),
                              ),
                            ),
                          );
              }
          }),
        );
  }
}